import axios from 'axios'
import ElMessage from './singleMsg'
import { useUserStore } from '../stores/user'
import router from '../router'
import {hexMD5} from './md5'
import { ElLoading } from 'element-plus'

// import md5 from 'js-md5'
const CancelToken = axios.CancelToken
const queue = [] // 请求队列
// 取消重复请求
const removeRepeatRequest = (config) => {
    for (const key in queue) {
      const index = +key
      const item = queue[key]
   
      if (
        item.url === config.url &&
        item.method === config.method &&
        JSON.stringify(item.params) === JSON.stringify(config.params) &&
        JSON.stringify(item.data) === JSON.stringify(config.data)
      ) {
        // 执行取消操作
        item.cancel('操作太频繁，请稍后再试')
        queue.splice(index, 1)
      }
    }
  }
  
// 设置全局的请求次数，请求的间隙
axios.defaults.retry = 2
axios.defaults.retryDelay = 1000000
// axios.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded';
// axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
// const baseURL = (process.env.NODE_ENV === "development") ? "http://117.139.164.238:34342" : `http://117.139.164.238:34342`;
const baseURL = (process.env.NODE_ENV === "development") ? "http://localhost:8080" : `http://183.221.0.153:35009`;
// 创建axios实例
const service = axios.create({
    baseURL, // api 的 base_url
    timeout: 2000000, // 请求超时时间
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        // 'Content-Type': 'application/json',
        'Accept': 'application/json',
        // 'Access-Control-Allow-Origin':'*'
        // 'ngrok-skip-browser-warning': true,
    },
    // withCredentials: true // 允许携带cookie
})

let loading = null

// service.defaults.headers["Content-Type"] = "application/json"// request拦截器
service.interceptors.request.use(
    config => {
        if (config.loading) {
            loading = ElLoading.service({ lock: true, text: 'Loading', background: 'rgba(255, 255, 255, 0.6)' })
        }
        var url = config.url
        // url=url.replace("/api","") 
        // if(url == '/app/file/material_upload'){
        //     config.headers['Content-Type'] = 'multipart/form-data'
        // }
        //重复请求
        removeRepeatRequest(config) 
        config.cancelToken = new CancelToken(c => {
            queue.push({
                url: config.url,
                method: config.method,
                params: config.params,
                data: config.data,
                cancel: c,
            })
        })
        //

        const userStore = useUserStore()
        console.log(userStore.token)
         if (userStore.token) {
            config.headers['Token'] = userStore.token // 让每个请求携带自定义token 请根据实际情况自行修改
        }
        if (userStore.orgId) {
            config.headers['orgId'] = userStore.orgId // 让每个请求携带自定义token 请根据实际情况自行修改
        }
        if (userStore.clientId) {
            config.headers['clientId'] = userStore.clientId // 让每个请求携带自定义token 请根据实际情况自行修改
        }
        if (userStore.apiHost) {
            config.baseURL = userStore.apiHost;
        }
        let timestamp = parseInt(new Date().getTime() / 1000); 
        //默认 
        // let appid="cb8608bbc9b1451a84e0d14054b4b09a"
        let appid="705ce6a3c42a4ec3a0d0dd7758d84216"
        let key="1232432324324324"
        let sign = hexMD5(`${appid}${url}${timestamp}${key}`)
        config.headers['Sign'] = sign // 关键所在
        config.headers['AppId'] = appid // 关键所在
        config.headers['Timestamp'] = timestamp // 关键所在  
        return config
    },
    error => {
        // Do something with request error
        Promise.reject(error)
    }
)
// response 拦截器
service.interceptors.response.use(
    response => {
        if (response.config.loading) {
            loading.close()
        }
        removeRepeatRequest(response.config)
        if (response.headers && (response.headers['content-type'] === 'application/x-msdownload' || response.headers['content-type'] === 'application/vnd.ms-excel'|| response.headers['content-type'] === 'application/zip'|| response.headers['content-type'] === 'application/octet-stream')) {
            return response.data;
        }
        const res = response.data
        if (res) {
            if (res.code == '200') { 
                return res
            } else {
                // 先提示错误信息
                // if (res.message) {
                //     ElMessage({ type: 'warning', message: res.message, offset: 100 })
                // }
                /**
                 * '700003' => '认证失败',
                 * '700004' => '当前用户已经过期(登录超时)'
                 */
                const userStore = useUserStore()
                switch (res.code) {
                    case '10000': // 刷新用户 token
                        // userStore.$reset()
                        break;
                    case '10001': // 登录超时，退出登录状态
                        // userStore.logOut()
                        // router.replace('/login')
                        break;
                    case '10002': // 登录超时，退出登录状态
                        // userStore.setUserToken(""); 
                        // router.replace('/login')
                        break;
                }
                return Promise.reject(res)
            }
        } else {
            // ElMessage({ type: 'warning', message: '请求成功，返回值错误', offset: 100 })
            return Promise.reject('error', response)
        }
    },
    error => {
        if (loading) {
            loading.close()
        }
        // http响应状态码
        const resposeCode = {
            '301': '请求需要重定向',
            '400': '网络错误，请重新尝试',
            '403': '请求被拒绝',
            '404': '请求资源不存在',
            '500': '服务器错误',
        }
        const response = error.response || { status: 400 }
        const status = response.status
        // ElMessage({ type: 'error', message:  resposeCode[status], offset: 100 })
        return Promise.reject(error)
    }
)

export default service

//只会调用一次接口，共享返回的promise
/*function query(requestHash, fun, ...params) {
    let res = Storage.get(requestHash);
    if (!res || res.code !== 0 || (Array.isArray(res.data) && res.data.length === 0)) {
        //不存在就请求
        return fun(...params).then(response => {
            Storage.set(requestHash, response, params[2]);
            return response;
        }).catch(function (error) {
            throw error;
        });
    } else {
        //存在就返回本地存储中的数据
        return res;
    }
}
export const http_share = (...params) => {
    var url = params[0];
    var requestHash = md5.hex(url + JSON.stringify(params));
    //var requestHash = new Md5().update(url + '[POST]' + qs.stringify(params)).digest('hex');
    return query(requestHash, service, ...params);
};*/
